package com.fdq.dianping.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fdq.dianping.entity.Result;
import com.fdq.dianping.entity.ShopComment;
import com.fdq.dianping.service.IShopCommentService;
import com.fdq.dianping.util.AliOss;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fdq
 * @since 2025-01-25
 */
@RestController
@RequestMapping("/shop-comment")
public class ShopCommentController {
    @Resource
    private IShopCommentService shopCommentService;

    @PostMapping("/insert")
    public Result insert(@RequestBody ShopComment shopComment){
        boolean save = shopCommentService.save(shopComment);
        if(save){
            return Result.success();
        }else {
            return Result.error("新增评论失败");
        }
    }

    /*
    * 查找某商户的评论
    * */
    @GetMapping("/getByShopId")
    public Result getByShopId(Long id){
        QueryWrapper<ShopComment> shopCommentQueryWrapper = new QueryWrapper<>();
        shopCommentQueryWrapper.eq("shop_id",id);
        List<ShopComment> shopComments = shopCommentService.list(shopCommentQueryWrapper);
        return Result.success(shopComments);
    }

    /*
    * 查找某人的评论
    * */
    @GetMapping("/getByUserId")
    public Result getByUserId(Long id){
        QueryWrapper<ShopComment> shopCommentQueryWrapper = new QueryWrapper<>();
        shopCommentQueryWrapper.eq("user_id",id);
        List<ShopComment> shopComments = shopCommentService.list(shopCommentQueryWrapper);
        return Result.success(shopComments);
    }

    /*
    * 上传评论的图片
    * */
    @PostMapping("/picUpload")
    public Result picUpload(MultipartFile pic) throws IOException {
        // 生成一个随机的UUID
        UUID uuid = UUID.randomUUID();
        // 将UUID转换为字符串
        String uuidString = uuid.toString();
        // 去掉连字符，生成一个纯随机字符串
        String randomString = uuidString.replace("-", "");
        String fileName = randomString+".jpg";
        String url = AliOss.upload(fileName, pic);
        return Result.success(url);
    }

    /*
    * 删除评论
    * */
    @DeleteMapping("/deleteById")
    public Result deleteById(Long id){
        boolean removed = shopCommentService.removeById(id);
        if(removed){
            return Result.success();
        }else {
            return Result.error("删除商户评论失败");
        }
    }
}
